package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.common.utils.PasswordUtil;
import com.bookmanger.common.utils.UserIdThreadLocal;
import com.bookmanger.entity.Book;
import com.bookmanger.entity.StuNo;
import com.bookmanger.entity.User;
import com.bookmanger.entity.dto.UserInfoDTO;
import com.bookmanger.entity.request.UserInfoRequest;
import com.bookmanger.entity.select.UserListDto;
import com.bookmanger.entity.vo.ListForm;
import com.bookmanger.entity.vo.UserListVo;
import com.bookmanger.mapper.UserMapper;
import com.bookmanger.service.StuNoService;
import com.bookmanger.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huangfuhao
 * @Date 2024/10/26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StuNoService stuNoService;

    /**
     * 使用token中得到的用户id查询用户信息
     *
     * @return
     */
    @Override
    public Result<UserInfoDTO> getUserInfo() {
        Long userId = UserIdThreadLocal.getUserId();
        if (userId == null) {
            return Result.unauthorizel("用户未登录");
        }
        User user = this.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        UserInfoDTO userInfoDTO = BeanUtil.copyProperties(user, UserInfoDTO.class);
        return Result.success(userInfoDTO);
    }

    /**
     * 更新用户信息
     *
     * @return
     */
    @Override
    public Result<String> updateUserInfo(UserInfoRequest userInfoRequest) {
        Long userId = UserIdThreadLocal.getUserId();
        if (userId == null) {
            return Result.unauthorizel("用户未登录");
        }
        User user = new User();
        if (StringUtils.isNotBlank(userInfoRequest.getPassword())) {
            user.setPassword(PasswordUtil.encodePassword(userInfoRequest.getPassword()));
        } else {
            user.setPassword(null);
        }
        if (StringUtils.isNotBlank(userInfoRequest.getEmail())) {
            user.setEmail(userInfoRequest.getEmail());
        } else {
            user.setEmail(null);
        }
        if (StringUtils.isNotBlank(userInfoRequest.getStuNo())) {
            //检查是否是原来的学号
            User one = lambdaQuery().eq(User::getId, userId).one();
            if (!userInfoRequest.getStuNo().equals(one.getStuNo())) {//不是原来的学号
                //查询学号是否在学号表中有
                LambdaQueryWrapper<StuNo> eq = new LambdaQueryWrapper<>();
                eq.eq(StuNo::getStuNo, userInfoRequest.getStuNo());
                StuNo stuNo = stuNoService.getOne(eq);
                if (stuNo == null) {
                    return Result.error("学号不存在");
                }
                //核对学号密码
                if (!stuNo.getPassword().equals(userInfoRequest.getStuNoPassword())) {
                    return Result.error("学号密码错误");
                }
                //绑学号检查一个学号只能绑一个人
                User one1 = lambdaQuery().eq(User::getStuNo, userInfoRequest.getStuNo()).one();
                if (one1 == null) {
                    user.setStuNo(userInfoRequest.getStuNo());
                } else {
                    return Result.error("学号已被绑定其它账号");
                }
            }
        } else {
            //检查有没有传学号密码
            if (StringUtils.isNotBlank(userInfoRequest.getStuNoPassword())) {//有学号密码才是操作学号
                //查询是否绑定了学号
                User one = lambdaQuery().eq(User::getId, userId).one();
                if (StringUtils.isNotBlank(one.getStuNo())) {//有绑定，进行解绑
                    //查询学号表
                    LambdaQueryWrapper<StuNo> eq = new LambdaQueryWrapper<>();
                    eq.eq(StuNo::getStuNo, one.getStuNo());
                    StuNo stuNo = stuNoService.getOne(eq);
                    if (stuNo == null) {
                        return Result.error("解绑失败，学号不存在，请联系管理员");
                    }
                    //核对学号密码
                    if (!stuNo.getPassword().equals(userInfoRequest.getStuNoPassword())) {
                        return Result.error("学号密码错误");
                    }
                    //学号为空，判断原来是否有绑定学号，有则是解绑操作，要有学号密码
                    user.setStuNo("");
                }
            }
        }
        user.setId(userId);
        user.setUsername(null);
        if (this.updateById(user)) {
            return Result.success("更新成功");
        }
        return Result.success("更新失败");
    }

    @Override
    public Result<ListForm<UserListVo>> getUserList(UserListDto userListDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //用户名查询
        if (StringUtils.isNotBlank(userListDto.getUsername())) {
            queryWrapper.eq("username", userListDto.getUsername());
        }
        //状态查询
        if (userListDto.getBanned() != null) {
            queryWrapper.eq("banned", userListDto.getBanned());
        }
        Page<User> userPage = new Page<>(userListDto.getPage(), userListDto.getSize());
        IPage<User> userIPage = page(userPage, queryWrapper);
        List<User> userList = userIPage.getRecords();
        List<UserListVo> userListVoList = userList.stream().map(user -> {
            UserListVo vo = new UserListVo();
            BeanUtil.copyProperties(user, vo);
            vo.setRole("user");
            return vo;
        }).toList();
        ListForm<UserListVo> userListForm = new ListForm<>(userListDto.getPage(), userListDto.getSize(),
                userIPage.getPages(), //总页数
                userIPage.getTotal(), //总记录数
                userListVoList);
        return Result.success(userListForm);
    }

    @Override
    public Result userDisable(Long id) {
        if (baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 2);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("停用成功");
        } else {
            return Result.error("停用失败");
        }
    }

    @Override
    public Result userEnable(Long id) {
        if (baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 0);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("解冻成功");
        } else {
            return Result.error("解冻失败");
        }
    }

    @Override
    public Result userFreeze(Long id) {
        if (baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 1);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("冻结成功");
        } else {
            return Result.error("冻结失败");
        }
    }

    @Override
    public List<User> getUserListByName(String userName) {
        return list(new LambdaQueryWrapper<User>()
                .like(User::getUsername, userName));
    }

    @Override
    public Result<Integer> getUserCount() {
        Long aLong = baseMapper.selectCount(null);
        return Result.success(aLong.intValue());
    }
}
